﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OAuth2.Repository.Model;
using OAuth2.Framework.Model;

namespace OAuth2.Repository
{
    public class InMemoryTokenRepository:ITokenRepository
    {
        static readonly IDictionary<string, AuthorizationGrant> GrantRepo = new Dictionary<string, AuthorizationGrant>();
        static readonly IDictionary<string, AccessToken> TokensRepo = new Dictionary<string, AccessToken>();
        static readonly IDictionary<string, RefreshTokenModel> RefreshTokenRepo = new Dictionary<string, RefreshTokenModel>();

        static InMemoryTokenRepository() 
        { 
            RefreshTokenRepo.Add("refresh",new RefreshTokenModel{
                 ClientID="1001",
                  Scope=new string[]{"create","view","delete"},
                  Token="refresh"
            });
        }

        #region ITokenRepository 成员

        public void AddAccessToken(AccessToken token)
        {
            TokensRepo.Add(token.Token, token);
        }

        public void AddAuthorizationGrant(AuthorizationGrant grant)
        {
            GrantRepo.Add(grant.Code,grant);
        }

        public AuthorizationGrant FindAuthorizationGrant(string authorizationCode)
        {
            if (!GrantRepo.ContainsKey(authorizationCode)) return null;
            return GrantRepo[authorizationCode];
        }

        public AuthorizationGrant FindAuthorizationGrant(string clientID, string resourceOwnerID)
        {
            return (from x in GrantRepo
                    where x.Value.client.ClientID.ToUpperInvariant() == clientID.ToUpperInvariant() &&
                    x.Value.ResourceOwnerID.ToUpperInvariant() == resourceOwnerID.ToUpperInvariant()
                    orderby x.Value.IssuedOn descending
                    select x.Value).FirstOrDefault();
        }

        public AccessTokenModel FindToken(string token)
        {
            if (!TokensRepo.ContainsKey(token))
                return null;
            return TokensRepo[token];
        }

        public RefreshTokenModel FindRefreshToken(string refreshToken)
        {
            if (!RefreshTokenRepo.ContainsKey(refreshToken))
                return null;
            return RefreshTokenRepo[refreshToken];
        }

        #endregion

    }
}
